<template>
  <div class="meeting-platform">
    <!-- 左侧录音区域 -->
    <div class="left-panel">
      <div class="recording-section">
        <div class="section-header">
          <h2>会议录音</h2>
          <div class="status-indicators">
            <div
              class="status-indicator"
              :class="{ active: connectionStatus === 'connected' }"
            >
              <div class="pulse-dot" />
              <span>{{
                connectionStatus === "connected"
                  ? "已连接"
                  : connectionStatus === "connecting"
                    ? "连接中"
                    : connectionStatus === "error"
                      ? "连接错误"
                      : "未连接"
              }}</span>
            </div>
            <div v-if="isRecording" class="status-indicator active">
              <div class="pulse-dot" />
              <span>录音中 {{ formatDuration(recordingDuration) }}</span>
            </div>
          </div>
        </div>

        <div class="recording-controls">
          <button class="control-btn" @click="recOpen()">打开录音</button>
          <button
            class="control-btn"
            :disabled="!rec || isRecording"
            @click="recStart()"
          >
            开始录音
          </button>
          <button
            class="control-btn"
            :disabled="!isRecording"
            @click="recStop()"
          >
            停止录音
          </button>
          <button class="control-btn" :disabled="!recBlob" @click="recPlay()">
            播放录音
          </button>
        </div>

        <div v-if="recwave" ref="recwave" class="wave-display" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue";
//必须引入的核心
import Recorder from "recorder-core";
//引入mp3格式支持文件；如果需要多个格式支持，把这些格式的编码引擎js文件放到后面统统引入进来即可
import "recorder-core/src/engine/mp3";
import "recorder-core/src/engine/mp3-engine";
//录制wav格式的用这一句就行
import "recorder-core/src/engine/wav";
import "recorder-core/src/engine/pcm";

// WebSocket状态常量
const WS_STATE = {
  CONNECTING: 0,
  OPEN: 1,
  CLOSING: 2,
  CLOSED: 3
} as const;

// WebSocket配置
const WS_CONFIG = {
  url: "ws://localhost:8082/",
  reconnectInterval: 3000,
  maxReconnectAttempts: 5,
  heartbeatInterval: 30000
};

let rec: any;
let recBlob: any;
let wave: any;
const recwave = ref(null);
let ws: any;
let reconnectAttempts = 0;
let reconnectTimer: any = null;
let heartbeatTimer: any = null;
let isRecording = ref(false);
let connectionStatus = ref("disconnected");
let recordingDuration = ref(0);
let recordingTimer: any = null;
let lastSendTime = 0; // 记录上次发送时间
const SEND_INTERVAL = 3000; // 发送间隔，10秒发送一次

// WebSocket连接管理
function connectWebSocket() {
  if (ws && ws.readyState === WS_STATE.OPEN) {
    console.log("WebSocket已连接");
    return;
  }

  try {
    ws = new WebSocket(WS_CONFIG.url);
    connectionStatus.value = "connecting";

    ws.onopen = () => {
      console.log("WebSocket连接成功");
      connectionStatus.value = "connected";
      reconnectAttempts = 0;
      startHeartbeat();
    };

    ws.onmessage = event => {
      handleWebSocketMessage(event);
    };

    ws.onclose = event => {
      console.log("WebSocket连接关闭:", event.code, event.reason);
      connectionStatus.value = "disconnected";
      stopHeartbeat();

      if (
        isRecording.value &&
        reconnectAttempts < WS_CONFIG.maxReconnectAttempts
      ) {
        scheduleReconnect();
      }
    };

    ws.onerror = error => {
      console.error("WebSocket错误:", error);
      connectionStatus.value = "error";
    };
  } catch (error) {
    console.error("创建WebSocket连接失败:", error);
    connectionStatus.value = "error";
  }
}

// 重连机制
function scheduleReconnect() {
  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
  }

  reconnectTimer = setTimeout(() => {
    reconnectAttempts++;
    console.log(
      `尝试重连 (${reconnectAttempts}/${WS_CONFIG.maxReconnectAttempts})`
    );
    connectWebSocket();
  }, WS_CONFIG.reconnectInterval);
}

// 关闭WebSocket连接
function closeWebSocket() {
  stopHeartbeat();

  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
    reconnectTimer = null;
  }

  if (ws && ws.readyState !== WS_STATE.CLOSED) {
    ws.close();
    ws = null;
  }

  connectionStatus.value = "disconnected";
  reconnectAttempts = 0;
}

// 处理WebSocket消息
function handleWebSocketMessage(event: MessageEvent) {
  try {
    const message = JSON.parse(event.data);
    console.log("收到WebSocket消息:", message);

    switch (message.type) {
      case "TRANSCRIPTION":
        console.log("转录结果:", message);
        break;
      default:
        console.log("未知消息类型:", message.type);
    }
  } catch (error) {
    console.error("解析WebSocket消息失败:", error);
  }
}

// 发送消息到WebSocket
function sendMessage(message: any) {
  if (!ws || ws.readyState !== WS_STATE.OPEN) {
    console.warn("WebSocket未连接，无法发送消息");
    return Promise.resolve(false);
  }

  try {
    ws.send(JSON.stringify(message));
    console.log("发送WebSocket消息成功:", message);
    return Promise.resolve(true);
  } catch (error) {
    console.error("发送WebSocket消息失败:", error);
    return Promise.resolve(false);
  }
}

// 向WebSocket发送音频数据
function sendAudioData(blob: any) {
  if (!ws || ws.readyState !== WS_STATE.OPEN) {
    console.warn("WebSocket未连接，无法发送音频数据");
    return Promise.resolve(false);
  }

  console.log("发送音频数据:", blob);

  const message = {
    type: "AUDIO_DATA",
    userId: "user1",
    data: blob.toString(),
    timestamp: Date.now()
  };

  return sendMessage(message);
}
// 心跳机制
function startHeartbeat() {
  if (heartbeatTimer) {
    clearInterval(heartbeatTimer);
  }

  heartbeatTimer = setInterval(() => {
    if (ws && ws.readyState === WS_STATE.OPEN) {
      sendMessage({
        type: "HEARTBEAT",
        userId: "user1",
        timestamp: Date.now()
      });
    }
  }, WS_CONFIG.heartbeatInterval);
}

function stopHeartbeat() {
  if (heartbeatTimer) {
    clearInterval(heartbeatTimer);
    heartbeatTimer = null;
  }
}

// 开始录音计时
function startRecordingTimer() {
  recordingDuration.value = 0;
  recordingTimer = setInterval(() => {
    recordingDuration.value += 1000;
  }, 1000);
}

// 停止录音计时
function stopRecordingTimer() {
  if (recordingTimer) {
    clearInterval(recordingTimer);
    recordingTimer = null;
  }
}

// 格式化录音时长
function formatDuration(ms: number) {
  const seconds = Math.floor(ms / 1000);
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
}

// 打开录音
function recOpen() {
  //创建录音对象
  rec = Recorder({
    type: "mp3", //录音格式，可以换成wav等其他格式
    sampleRate: 16000, //录音的采样率，越大细节越丰富越细腻
    bitRate: 16, //录音的比特率，越大音质越好
    onProcess: (
      buffers: any,
      powerLevel: any,
      bufferDuration: any,
      bufferSampleRate: any,
      newBufferIdx: any,
      asyncEnd: any
    ) => {
      //录音实时回调，大约1秒调用12次本回调
      //可实时绘制波形，实时上传（发送）数据
      //console.log("录音实时回调", buffers, powerLevel, bufferDuration);
      // 控制发送频率，每10秒发送一次
      const currentTime = Date.now();
      if (currentTime - lastSendTime >= SEND_INTERVAL) {
        sendAudioData(buffers[buffers.length - 1])
          .then(() => {
            console.log("已发送录音数据");
            lastSendTime = currentTime; // 更新发送时间
          })
          .catch(error => {
            console.error("发送录音数据失败:", error);
          });
      }
      if (wave) {
        wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate);
      }
    }
  });
  if (!rec) {
    alert("当前浏览器不支持录音功能！");
    return;
  }
  //打开录音，获得权限
  rec.open(
    () => {
      //console.log("录音已打开");
      if (recwave.value) {
        //创建音频可视化图形绘制对象
        wave = Recorder.WaveView({ elem: recwave.value });
      }
      //开启webSocket
      connectWebSocket();
    },
    (msg: any, isUserNotAllow: any) => {
      //用户拒绝了录音权限，或者浏览器不支持录音
      //console.log((isUserNotAllow ? "UserNotAllow，" : "") + "无法录音:" + msg);
    }
  );
}
// 开始录音
function recStart() {
  if (!rec) {
    //console.error("未打开录音");
    return;
  }
  rec.start();
  startRecordingTimer();
  isRecording.value = true;
  lastSendTime = 0; // 重置发送时间
  //console.log("已开始录音");
}
// 结束录音
function recStop() {
  if (!rec) {
    console.error("未打开录音");
    return;
  }
  rec.stop(
    (blob: any, duration: any) => {
      //blob就是我们要的录音文件对象，可以上传，或者本地播放
      recBlob = blob;
      //简单利用URL生成本地文件地址，此地址只能本地使用，比如赋值给audio.src进行播放，赋值给a.href然后a.click()进行下载（a需提供download="xxx.mp3"属性）
      const localUrl = (window.URL || window.webkitURL).createObjectURL(blob);
      console.log("录音成功", blob, localUrl, "时长:" + duration + "ms");
      upload(blob); //把blob文件上传到服务器
      rec.close(); //关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
      rec = null;
      stopRecordingTimer();
      isRecording.value = false;
    },
    (err: any) => {
      console.error("结束录音出错：" + err);
      rec.close(); //关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
      rec = null;
      stopRecordingTimer();
      isRecording.value = false;
    }
  );
}

// 上传录音
function upload(blob: any) {
  //使用FormData用multipart/form-data表单上传文件
  //或者将blob文件用FileReader转成base64纯文本编码，使用普通application/x-www-form-urlencoded表单上传
  // const form = new FormData();
  // form.append('upfile', blob, 'recorder.mp3'); // 和普通form表单并无二致，后端接收到upfile参数的文件，文件名为recorder.mp3
  // form.append('key', 'value'); // 其他参数
  // var xhr = new XMLHttpRequest();
  // xhr.open('POST', '/upload/xxxx');
  // xhr.onreadystatechange = () => {
  //   if (xhr.readyState == 4) {
  //     if (xhr.status == 200) {
  //       console.log('上传成功');
  //     } else {
  //       console.error('上传失败' + xhr.status);
  //     }
  //   }
  // };
  // xhr.send(form);
}
// 本地播放录音
function recPlay() {
  //本地播放录音试听，可以直接用URL把blob转换成本地播放地址，用audio进行播放
  const localUrl = URL.createObjectURL(recBlob);
  const audio = document.createElement("audio");
  audio.controls = true;
  document.body.appendChild(audio);
  audio.src = localUrl;
  audio.play(); //这样就能播放了
  //注意不用了时需要revokeObjectURL，否则霸占内存
  setTimeout(function () {
    URL.revokeObjectURL(audio.src);
  }, 5000);
}

// 组件卸载时清理资源
onUnmounted(() => {
  if (rec) {
    rec.close();
    rec = null;
  }

  if (recordingTimer) {
    clearInterval(recordingTimer);
    recordingTimer = null;
  }

  closeWebSocket();
});
</script>

<style scoped>
@keyframes pulse {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }

  100% {
    opacity: 1;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@keyframes bounce {
  0%,
  80%,
  100% {
    transform: scale(0);
  }

  40% {
    transform: scale(1);
  }
}

/* 响应式设计 */
@media (width <= 768px) {
  .meeting-platform {
    flex-direction: column;
    height: auto;
    min-height: 100vh;
  }

  .left-panel,
  .right-panel {
    padding: 20px;
  }

  .mic-button {
    padding: 20px;
  }

  .mic-icon {
    width: 36px;
    height: 36px;
  }
}

.meeting-platform {
  display: flex;
  gap: 20px;
  height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.left-panel,
.right-panel {
  flex: 1;
  padding: 30px;
  overflow: hidden;
  background: rgb(255 255 255 / 95%);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgb(0 0 0 / 10%);
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
}

.section-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.status-indicators {
  display: flex;
  gap: 15px;
  align-items: center;
}

.status-indicator {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 500;
  color: #6c757d;
  background: #f8f9fa;
  border-radius: 20px;
}

.status-indicator.active {
  color: #155724;
  background: #d4edda;
}

.pulse-dot {
  width: 8px;
  height: 8px;
  background: #6c757d;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.status-indicator.active .pulse-dot {
  background: #28a745;
}

.connection-status {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 500;
  color: #6c757d;
  background: #f8f9fa;
  border-radius: 20px;
}

.connection-status.connected {
  color: #155724;
  background: #d4edda;
}

.status-dot {
  width: 8px;
  height: 8px;
  background: #6c757d;
  border-radius: 50%;
}

.connection-status.connected .status-dot {
  background: #28a745;
}

.recording-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
}

.control-btn {
  padding: 12px 20px;
  font-size: 14px;
  font-weight: 500;
  color: white;
  cursor: pointer;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.control-btn:hover:not(:disabled) {
  box-shadow: 0 5px 15px rgb(102 126 234 / 30%);
  transform: translateY(-1px);
}

.control-btn:disabled {
  cursor: not-allowed;
  opacity: 0.6;
  transform: none;
}

.control-btn.danger {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

.control-btn.danger:hover:not(:disabled) {
  box-shadow: 0 5px 15px rgb(231 76 60 / 30%);
}

.wave-display {
  width: 100%;
  height: 200px;
  margin-top: 20px;
  background: #f8f9fa;
  border-radius: 12px;
}

.audio-format-selector {
  display: flex;
  gap: 10px;
  align-items: center;
  padding: 10px 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.audio-format-selector label {
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.format-select {
  padding: 6px 12px;
  font-size: 14px;
  color: #495057;
  cursor: pointer;
  background: white;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.format-select:hover {
  border-color: #667eea;
}

.format-select:focus {
  border-color: #667eea;
  outline: none;
  box-shadow: 0 0 0 2px rgb(102 126 234 / 20%);
}

.format-info {
  margin-top: 5px;
  font-size: 12px;
  color: #6c757d;
}

.info-text {
  font-style: italic;
}

.recording-quality {
  display: flex;
  gap: 15px;
  align-items: center;
  padding: 10px 16px;
  margin-top: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.quality-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.quality-label {
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.quality-value {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
}

.download-btn {
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 500;
  color: white;
  cursor: pointer;
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  border: none;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.download-btn:hover {
  box-shadow: 0 5px 15px rgb(40 167 69 / 30%);
  transform: translateY(-1px);
}

.mic-button {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
  padding: 30px;
  color: white;
  cursor: pointer;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  box-shadow: 0 10px 30px rgb(102 126 234 / 30%);
  transition: all 0.3s ease;
}

.mic-button:hover {
  box-shadow: 0 15px 40px rgb(102 126 234 / 40%);
  transform: translateY(-2px);
}

.mic-button.recording {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
  box-shadow: 0 10px 30px rgb(231 76 60 / 30%);
  animation: pulse 2s infinite;
}

.mic-icon {
  width: 48px;
  height: 48px;
}

.mic-icon svg {
  width: 100%;
  height: 100%;
}

.recording-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: center;
}

.timer {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.audio-level {
  display: flex;
  gap: 3px;
  align-items: end;
  height: 60px;
}

.level-bar {
  width: 4px;
  background: linear-gradient(to top, #667eea, #764ba2);
  border-radius: 2px;
  transition: height 0.1s ease;
}

.transcription-section {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.section-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.section-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.controls {
  display: flex;
  gap: 10px;
}

.clear-btn,
.copy-btn {
  padding: 6px 12px;
  font-size: 12px;
  color: #6c757d;
  cursor: pointer;
  background: #f8f9fa;
  border: none;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.clear-btn:hover,
.copy-btn:hover {
  color: #495057;
  background: #e9ecef;
}

.transcription-content {
  flex: 1;
  min-height: 300px;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
  border-radius: 12px;
}

.text-content {
  line-height: 1.6;
  color: #2c3e50;
  white-space: pre-wrap;
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.transcription-message {
  padding: 16px;
  background: white;
  border-left: 4px solid #667eea;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.message-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #6c757d;
}

.user-id {
  padding: 2px 8px;
  font-weight: 500;
  color: white;
  background: #667eea;
  border-radius: 12px;
}

.timestamp {
  color: #adb5bd;
}

.message-content {
  font-size: 14px;
  line-height: 1.6;
  color: #2c3e50;
}

.placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #6c757d;
  text-align: center;
}

.placeholder-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.generate-btn {
  padding: 12px 24px;
  font-weight: 500;
  color: white;
  cursor: pointer;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.generate-btn:hover:not(:disabled) {
  box-shadow: 0 5px 15px rgb(102 126 234 / 30%);
  transform: translateY(-1px);
}

.generate-btn:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.loading {
  display: flex;
  gap: 8px;
  align-items: center;
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.summary-content {
  flex: 1;
  overflow-y: auto;
}

.summary-results {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.summary-item {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
}

.summary-item h4 {
  margin: 0 0 15px;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.key-points,
.action-items {
  padding: 0;
  margin: 0;
  list-style: none;
}

.key-points li,
.action-items li {
  padding: 8px 0;
  color: #495057;
  border-bottom: 1px solid #e9ecef;
}

.key-points li:last-child,
.action-items li:last-child {
  border-bottom: none;
}

.action-items li {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.action-owner {
  padding: 4px 8px;
  font-size: 12px;
  font-weight: 500;
  color: white;
  background: #667eea;
  border-radius: 4px;
}

.summary-text {
  margin: 0;
  line-height: 1.6;
  color: #495057;
}

.generating-placeholder,
.empty-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #6c757d;
  text-align: center;
}

.loading-animation {
  margin-bottom: 20px;
}

.loading-dots {
  display: flex;
  gap: 8px;
}

.dot {
  width: 12px;
  height: 12px;
  background: #667eea;
  border-radius: 50%;
  animation: bounce 1.4s ease-in-out infinite both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}
</style>
